package com.jiyun.purse.controller;


import com.alibaba.fastjson.JSONObject;
import com.jiyun.purse.service.IFileService;
import com.jiyun.purse.util.HttpUtils;
import com.jiyun.result.Result;
import com.jiyun.purse.vo.CertificationVo;
import com.jiyun.purse.vo.FileVo;
import com.jiyun.purse.vo.OSSFile;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


/**
 * 文件请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/file")
public class FileController {
    /**
     * 字符常量：斜杠 {@code '/'}
     */
    public static final char SLASH = '/';

    /**
     * 字符常量：反斜杠 {@code '\\'}
     */
    public static final char BACKSLASH = '\\';

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private IFileService FileService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public Result upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = FileService.uploadFile(file);
            OSSFile ossFile = new OSSFile();
            ossFile.setName(getName(url));
            ossFile.setUrl(url);
            return Result.ok(ossFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return Result.error("上传失败");
        }
    }


    public static String getName(String filePath) {
        if (null == filePath) {
            return null;
        }
        int len = filePath.length();
        if (0 == len) {
            return filePath;
        }
        if (isFileSeparator(filePath.charAt(len - 1))) {
            // 以分隔符结尾的去掉结尾分隔符
            len--;
        }

        int begin = 0;
        char c;
        for (int i = len - 1; i > -1; i--) {
            c = filePath.charAt(i);
            if (isFileSeparator(c)) {
                // 查找最后一个路径分隔符（/或者\）
                begin = i + 1;
                break;
            }
        }

        return filePath.substring(begin, len);
    }

    public static boolean isFileSeparator(char c) {
        return SLASH == c || BACKSLASH == c;
    }

    @RequestMapping("idc")
    public Object findMethod(@RequestBody FileVo fileVo) throws Exception {
        String host = "https://idcodeocr.market.alicloudapi.com";
        String path = "/idcodeocr";
        String method = "POST";
        String appcode = "182e9b57bda94ca8a8cbaa0b75f3ee27";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("img", fileVo.getUrl());
        bodys.put("side", "front");
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String msg = new String(EntityUtils.toString(response.getEntity()).getBytes(), "UTF-8");
            JSONObject object = JSONObject.parseObject(msg);
            return object;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("验证失败");
        }
    }

    @RequestMapping("idcCheck")
    public Object idcCheck(@RequestBody CertificationVo certificationVo) throws Exception {
        String host = "https://jmidcardv1.market.alicloudapi.com";
        String path = "/idcard/validate";
        String method = "POST";
        String appcode = "182e9b57bda94ca8a8cbaa0b75f3ee27";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idCardNo", certificationVo.getIdcard());
        bodys.put("name", certificationVo.getName());

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String msg = new String(EntityUtils.toString(response.getEntity()).getBytes(), "UTF-8");
            JSONObject object = JSONObject.parseObject(msg);
            return object;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("验证失败");
        }
    }
}